import Cookies from 'js-cookie'

import { listsCode } from '@/api/country'
import { getUnitList } from '@/api/base/product'

const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },

  device: 'desktop',
  size: Cookies.get('size') || 'medium',

  country: [],
  unit: [],
  linkList: []
}

const mutations = {
  SET_LINK: (state, linkList) => {
    state.linkList = linkList
  },
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SET_SIZE: (state, size) => {
    state.size = size
    Cookies.set('size', size)
  },

  /**
   * @param {typeof state} state
   * @param {any[]} country
   */
  SET_COUNTRY: (state, country) => {
    state.country = country
  },

  /**
   * @param {typeof state} state
   * @param {any[]} unit
   */
  SET_UNIT: (state, unit) => {
    state.unit = unit
  }
}

const actions = {
  setLink({ commit }, linkList) {
    commit('SET_LINK', linkList)
  },
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setSize({ commit }, size) {
    commit('SET_SIZE', size)
  },

  setCountry({ commit }, country) {
    commit('SET_COUNTRY', country)
  },

  async getCountry({ commit, state }) {
    // 国家列表
    if (state.country.length === 0) {
      // 获取国家列表
      const countryResponse = await listsCode({
        page: 1,
        limit: 200
      })

      commit('SET_COUNTRY', countryResponse.data.lists)
      return Promise.resolve(countryResponse.data.lists)
    } else {
      return Promise.resolve(state.country)
    }
  },

  setUnit({ commit }, unit) {
    commit('SET_UNIT', unit)
  },

  async getUnit({ commit, state }) {
    // 单位
    if (state.unit.length === 0) {
      const unitResponse = await getUnitList()
      console.log('unitResponse', unitResponse)
      commit('SET_UNIT', unitResponse.data)
      return Promise.resolve(unitResponse.data)
    } else {
      return Promise.resolve(state.unit)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
